package com.huafeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huafeng.commonutil.CheckUtils;
import com.huafeng.mapper.SysRoleMapper;
import com.huafeng.model.base.Result;
import com.huafeng.model.entity.SysRole;
import com.huafeng.model.entity.SysUserRole;
import com.huafeng.model.vo.AssignRoleVo;
import com.huafeng.model.vo.SysRoleQueryVo;
import com.huafeng.service.SysRoleService;
import com.huafeng.service.SysUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/15 20:38
 * @Description SysRoleServiceImpl
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysUserRoleService sysUserRoleService;

    private ReentrantLock assignLock = new ReentrantLock();

    @Override
    public Result findAllRole() {
        List<SysRole> sysRoles = this.query().list();
        return Result.ok(sysRoles);
    }

    @Override
    public Result queryRolesByPage(SysRoleQueryVo sysRoleQueryVo) {
        // 创建分页对象
        Page<SysRole> sysRolePage = new Page<>(sysRoleQueryVo.getPage(), sysRoleQueryVo.getLimit());

        // 获取查询参数
        String roleName = sysRoleQueryVo.getRoleName();

        // 创建查询对象
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        Map<String,String> params = new HashMap<>();
        params.put("role_name",roleName);
        queryWrapper = CheckUtils.checkParams(queryWrapper,sysRoleQueryVo,params);

        // 分页条件查询
        sysRolePage = this.page(sysRolePage, queryWrapper);
        return Result.ok(sysRolePage);
    }

    @Override
    public Result toAssign(Long userId) {
        List<SysUserRole> sysUserRoleList = sysUserRoleService.query().eq("user_id", userId).list();
        // 从SYSUserRoleList中获取其所有角色id
        List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        // 查询所有角色
        List<SysRole> sysRoleList = this.query().list();

        Map<String, List<?>> resultMap = Map.of("allRoles", sysRoleList, "userRoleIds", roleIdList);
        return Result.ok(resultMap);
    }

    @Override
    public Result doAssign(AssignRoleVo assignRoleVo) {
        assignLock.lock();
        try {
            // 获取参数
            Long userId = assignRoleVo.getUserId();
            List<Long> roleIdList = assignRoleVo.getRoleIdList();

            Assert.isTrue(userId != null && userId > 0,"id must not be null and greater than zero");
            Assert.isTrue(!roleIdList.isEmpty(),"roleIdList must have values");

            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserRole::getUserId,userId);
            // 删除用户原有角色
            sysUserRoleService.remove(queryWrapper);

            // 更新用户角色
            List<SysUserRole> sysUserRoles = roleIdList.stream().map(roleId -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                return sysUserRole;
            }).collect(Collectors.toList());

            boolean saveBatch = sysUserRoleService.saveBatch(sysUserRoles);
            return CheckUtils.check(saveBatch);
        } finally {
            assignLock.unlock();
        }

    }
}
